#!/bin/bash

# YxYWeb 启动脚本
# 适用于生产环境

set -e  # 遇到错误立即退出

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 项目配置
PROJECT_NAME="YxYWeb"
PROJECT_DIR=$(dirname "$(readlink -f "$0")")
PID_FILE="$PROJECT_DIR/yxyweb.pid"
LOG_FILE="$PROJECT_DIR/logs/yxyweb.log"
PORT=8000

# 创建日志目录
mkdir -p "$PROJECT_DIR/logs"

# 检查服务是否已运行
check_running() {
    if [ -f "$PID_FILE" ]; then
        PID=$(cat "$PID_FILE")
        if ps -p "$PID" > /dev/null 2>&1; then
            log_warning "服务已在运行 (PID: $PID)"
            return 0
        else
            log_info "发现过期的PID文件，删除中..."
            rm -f "$PID_FILE"
        fi
    fi
    return 1
}

# 检查端口是否被占用
check_port() {
    if netstat -tuln 2>/dev/null | grep -q ":$PORT "; then
        log_warning "端口 $PORT 已被占用"
        return 0
    fi
    return 1
}

# 检查虚拟环境
check_venv() {
    if [ ! -d "$PROJECT_DIR/yxyweb_venv" ]; then
        log_error "虚拟环境不存在，请先运行 ./install.sh"
        exit 1
    fi
}

# 检查环境文件
check_env() {
    if [ ! -f "$PROJECT_DIR/.env" ]; then
        log_warning "环境配置文件不存在，将使用默认配置"
    fi
}

# 检查依赖
check_dependencies() {
    log_info "检查Python依赖..."
    
    # 激活虚拟环境
    source "$PROJECT_DIR/yxyweb_venv/bin/activate"
    
    # 检查关键依赖
    python3 -c "
import sys
required_packages = [
    'fastapi', 'uvicorn', 'sqlalchemy', 'aiomysql', 
    'pydantic', 'requests', 'psutil', 'nltk'
]

missing_packages = []
for package in required_packages:
    try:
        __import__(package)
    except ImportError:
        missing_packages.append(package)

if missing_packages:
    print(f'缺少依赖包: {missing_packages}')
    sys.exit(1)
else:
    print('所有依赖检查通过')
" || {
        log_error "依赖检查失败，请运行 ./install.sh 重新安装"
        exit 1
    }
}

# 设置环境变量
setup_environment() {
    log_info "设置环境变量..."
    
    # 设置NLTK数据路径
    export NLTK_DATA="/usr/local/nltk_data"
    
    # 设置Python路径
    export PYTHONPATH="$PROJECT_DIR:$PYTHONPATH"
    
    # 确保项目根目录在Python路径中
    cd "$PROJECT_DIR"
    
    # 设置环境
    export ENVIRONMENT="production"
    
    # 加载.env文件
    if [ -f "$PROJECT_DIR/.env" ]; then
        set -a
        source "$PROJECT_DIR/.env"
        set +a
    fi
    
    log_success "环境变量设置完成"
}

# 启动服务
start_service() {
    log_info "启动 $PROJECT_NAME 服务..."
    
    # 切换到项目目录
    cd "$PROJECT_DIR"
    
    # 激活虚拟环境
    source yxyweb_venv/bin/activate
    
    # 启动服务（后台运行）
    nohup python3 startup.py > "$LOG_FILE" 2>&1 &
    
    # 保存PID
    echo $! > "$PID_FILE"
    
    # 等待服务启动
    log_info "等待服务启动..."
    sleep 3
    
    # 检查服务是否启动成功
    if ps -p $(cat "$PID_FILE") > /dev/null 2>&1; then
        log_success "服务启动成功 (PID: $(cat "$PID_FILE"))"
        log_info "服务地址: http://localhost:$PORT"
        log_info "健康检查: http://localhost:$PORT/health"
        log_info "日志文件: $LOG_FILE"
    else
        log_error "服务启动失败，请检查日志: $LOG_FILE"
        exit 1
    fi
}

# 显示服务状态
show_status() {
    if [ -f "$PID_FILE" ]; then
        PID=$(cat "$PID_FILE")
        if ps -p "$PID" > /dev/null 2>&1; then
            log_success "服务运行中 (PID: $PID)"
            log_info "端口: $PORT"
            log_info "日志: $LOG_FILE"
            
            # 显示进程信息
            echo
            log_info "进程信息:"
            ps -p "$PID" -o pid,ppid,cmd,etime,pcpu,pmem
        else
            log_warning "PID文件存在但进程未运行"
        fi
    else
        log_info "服务未运行"
    fi
}

# 显示帮助信息
show_help() {
    echo "用法: $0 [选项]"
    echo
    echo "选项:"
    echo "  start     启动服务 (默认)"
    echo "  status    显示服务状态"
    echo "  help      显示此帮助信息"
    echo
    echo "示例:"
    echo "  $0         # 启动服务"
    echo "  $0 start   # 启动服务"
    echo "  $0 status  # 查看状态"
}

# 主函数
main() {
    case "${1:-start}" in
        "start")
            echo "=========================================="
            echo "    启动 $PROJECT_NAME 服务"
            echo "=========================================="
            echo
            
            # 检查服务是否已运行
            if check_running; then
                show_status
                exit 0
            fi
            
            # 检查端口
            if check_port; then
                log_error "端口 $PORT 被占用，请先停止占用该端口的服务"
                exit 1
            fi
            
            # 执行检查
            check_venv
            check_env
            check_dependencies
            setup_environment
            
            # 启动服务
            start_service
            
            echo
            echo "=========================================="
            log_success "服务启动完成！"
            echo "=========================================="
            echo
            echo "服务信息:"
            echo "  地址: http://localhost:$PORT"
            echo "  健康检查: http://localhost:$PORT/health"
            echo "  日志文件: $LOG_FILE"
            echo "  PID文件: $PID_FILE"
            echo
            echo "管理命令:"
            echo "  查看状态: $0 status"
            echo "  停止服务: ./stop.sh"
            echo "  重启服务: ./restart.sh"
            echo "  查看日志: tail -f $LOG_FILE"
            ;;
        "status")
            show_status
            ;;
        "help"|"-h"|"--help")
            show_help
            ;;
        *)
            log_error "未知选项: $1"
            show_help
            exit 1
            ;;
    esac
}

# 执行主函数
main "$@"
